﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Updater
{
    public class Utility
    {
        private static object _lockObj = new object();

        public static void ReportError(string errorMethod, Exception ex)
        {
            StringBuilder errmsg = new System.Text.StringBuilder(128);
            Exception tmpEx;

            try
            {
                errmsg.Append(errorMethod + ":");
                tmpEx = ex;

                while (tmpEx != null)
                {
                    errmsg.AppendLine();
                    errmsg.AppendLine();
                    errmsg.AppendLine("Type:      " + tmpEx.GetType().FullName);
                    errmsg.AppendLine("Message:   " + tmpEx.Message);
                    errmsg.AppendLine("StackTrace:" + tmpEx.StackTrace);

                    tmpEx = tmpEx.InnerException;
                }

                WriteLog(errmsg.ToString());

            }
            catch
            {
            }
        }

        public static void WriteLog(string logEntry)
        {
            try
            {
                string fileName = null;
                string filePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "log");
                FileStream fs = default(FileStream);
                StreamWriter sw = default(StreamWriter);

                lock (_lockObj)
                {
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    fileName = "error_log_";
                    fileName += string.Format("{0}_{1}_{2}.log", DateTime.Now.Year, DateTime.Now.Month.ToString("00"), DateTime.Now.Day.ToString("00"));
                    filePath = Path.Combine(filePath, fileName);

                    if (File.Exists(filePath))
                    {
                        fs = File.Open(filePath, FileMode.Append);
                    }
                    else
                    {
                        fs = File.Open(filePath, FileMode.CreateNew);
                    }

                    sw = new StreamWriter(fs);

                    try
                    {
                        sw.WriteLine(string.Format("-------------------------{0}:{1}:{2}-------------------------", DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second));

                        sw.Write(logEntry);
                        sw.WriteLine("\r\n-------------------------------------------------------------");
                    }
                    finally
                    {
                        sw.Close();
                    }
                }
            }
            catch
            {
            }
        }

    }
}
